package com.xuchen.zhenyang.controller.sys;

import cn.hutool.core.util.StrUtil;
import com.xuchen.zhenyang.controller.base.BaseController;
import com.xuchen.zhenyang.core.redis.RedisKey;
import com.xuchen.zhenyang.core.redis.RedisStore;
import com.xuchen.zhenyang.entity.SysUser;
import com.xuchen.zhenyang.model.ParentMenu;
import com.xuchen.zhenyang.service.SysMenuService;
import com.xuchen.zhenyang.util.MyUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController extends BaseController {


    @Autowired
    SysMenuService sysMenuService;

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @GetMapping("/error")
    String error() {
        return "error";
    }


    @GetMapping({"/", "/index", ""})
    String menuList(HttpServletRequest request) {
        List<ParentMenu> list = sysMenuService.getMenuByUserId(getSessionUser().getId());
        request.setAttribute("menuList", list);
        request.setAttribute("userName", getSessionUser().getUserName());
        return "index";
    }

    @PostMapping("/doLogin")
    String login(SysUser loginEntity, HttpServletRequest request, RedirectAttributes attributes) {
        if (getSessionUser()!=null){
            return "redirect:index";
        }
        String ip = MyUtils.getIpAddress(request);
        logger.info("[" + loginEntity.getUserName() + "]登录,IP[" + ip + "]");
        if (StrUtil.hasBlank(loginEntity.getUserName(),loginEntity.getPassword())) {
            return "redirect:login";
        }
        Integer loginCount = RedisStore.getValue(RedisKey.LOGIN_IP + ip);
        if (loginCount != null && loginCount == 5) {
            attributes.addFlashAttribute("msg", "用户尝试登录次数过多，请稍后再试");
            return "redirect:login";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(loginEntity.getUserName(), loginEntity.getPassword());
        try {
            SecurityUtils.getSubject().login(token);
        } catch (LockedAccountException lae) {
            token.clear();
            attributes.addFlashAttribute("msg", "用户已经被锁定不能登录，请与管理员联系！");
            return "redirect:login";
        } catch (AuthenticationException e) {
            token.clear();
            loginCount = RedisStore.getValue(RedisKey.LOGIN_IP + ip);
            RedisStore.setValue(RedisKey.LOGIN_IP + ip, (loginCount == null ? 0 : loginCount) + 1, 30, TimeUnit.MINUTES);
            attributes.addFlashAttribute("msg", "用户或密码不正确！还可尝试" + (5 - (loginCount == null ? 0 : loginCount)) + "次");
            return "redirect:login";
        }
        RedisStore.delKey(RedisKey.LOGIN_IP + MyUtils.getIpAddress(request));
        logger.info("[" + loginEntity.getUserName() + "]登录成功,IP[" + MyUtils.getIpAddress(request) + "]");
        return "redirect:index";
    }


}
